package com.duowei.diandan.print3;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.hardware.usb.UsbManager;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.duowei.diandan.app.App;
import com.duowei.diandan.app.OrderList;
import com.duowei.diandan.bean.Payment;
import com.duowei.diandan.bean.QrCodePay;
import com.duowei.diandan.constant.PayType;
import com.duowei.diandan.db.AppDatabase;
import com.duowei.diandan.db.entry.Jgsz;
import com.duowei.diandan.db.entry.Wmlsb;
import com.duowei.diandan.db.entry.Wmlsbjb;
import com.printsdk.cmd.PrintCmd;
import com.printsdk.usbsdk.UsbDriver;

import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Locale;

public class Print3 {
    private static final String TAG = "Print3";

    private final int SERIAL_BAUDRATE = UsbDriver.BAUD115200;
    private static Print3 sPrint3;

    private UsbDriver mUsbDriver;
    private boolean mConnected = false;

    private Print3() {
    }

    public static Print3 getInstance() {
        if (sPrint3 == null) {
            sPrint3 = new Print3();
        }
        return sPrint3;
    }

    public void connect(OnConnectListener listener) {
        Context context = App.getApp();
        mUsbDriver = new UsbDriver((UsbManager) context.getSystemService(Context.USB_SERVICE), context);
        Utils.getDriver(mUsbDriver, mUsbReceiver, context);
        if (mUsbDriver.openUsbDevice(SERIAL_BAUDRATE)) {
            mConnected = true;
//                Toast.makeText(mApp, "内置打印机连接成功", Toast.LENGTH_SHORT).show();

            if (listener != null) {
                listener.onConnected();
            }

        } else {
            mConnected = false;
            Toast.makeText(context, "内置打印机连接失败", Toast.LENGTH_SHORT).show();
        }
    }

    public boolean isConnected() {
        return mConnected;
    }

    private BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
                mUsbDriver.usbAttached(intent);
                mUsbDriver.openUsbDevice(SERIAL_BAUDRATE);
            } else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
                mUsbDriver.usbDetached(intent);
            }
        }
    };

    public void print(Wmlsbjb wmlsbjb, List<Wmlsb> wmlsbList, boolean isCommit) {
        try {
            print(PrintCmd.SetAlignment(0));
            print(PrintCmd.SetLeftmargin(0));
            print(PrintCmd.SetSizetext(0, 0));
            print(PrintCmd.SetLinespace(30));

            Jgsz jgsz = AppDatabase.getDatabase().jgszDao().findOne();
            if (jgsz != null && !TextUtils.isEmpty(jgsz.getBmmc())) {
                print(PrintCmd.SetAlignment(1));
                print(jgsz.getBmmc() + "\n\n");
            }

            print(PrintCmd.SetAlignment(0));
            print(PrintCmd.SetLeftmargin(100));
            print("桌号:" + wmlsbjb.getZh() + "\n");
            print("账单号:" + wmlsbjb.getWmdbh() + "\n");
            print("日期:" + wmlsbjb.getJysj().toString("yyyy-MM-dd HH:mm:ss") + "\n");

            print("--------------------------------\n");
            print(String.format(Locale.CHINA, "%-14s%4s%5s\n", "单品名称", "数量", "金额"));
            for (Wmlsb w : wmlsbList) {
                print(String.format(Locale.CHINA, "%-16s%5s￥%7s\n", w.getXmmc(), w.getSl(), w.getDj()));
                if (!TextUtils.isEmpty(w.getPz())) {
                    print(w.getPz() + "\n");
                }
            }
            print("--------------------------------\n");

            if (isCommit) {
                print(String.format(Locale.CHINA, "消费合计: ￥%.2f\n", wmlsbjb.getYs()));
                print("--------------------------------\n");
            } else {
                print(String.format(Locale.CHINA, "消费总额: ￥%.2f\n", wmlsbjb.getYsje()));
                print(String.format(Locale.CHINA, "折扣金额: ￥%.2f\n", wmlsbjb.getZk()));
                print(String.format(Locale.CHINA, "应收金额: ￥%.2f\n", wmlsbjb.getYs()));
                print("-------------------------------\n");

                List<Payment> paymentList = OrderList.getInstance().getPaymentList();
                if (paymentList != null && paymentList.size() > 0) {
                    for (Payment p : paymentList) {
                        if (p.payType == PayType.STORED_VALUE_TYPE) {
                            print(String.format(Locale.CHINA, "%s  ￥%.2f\n", p.title, p.payMoney));
                        } else if (p.payType == PayType.INTEGRAL_TYPE) {
                            print(p.title + "  " + p.jfValue + "\n");
                        } else if (p.payType == PayType.COUPON_TYPE) {
                            print(p.title + "  " + p.ticketNum + "张\n");
                        }
                    }
                }

                QrCodePay qrCodePay = OrderList.getInstance().getQrCodePay();
                if (qrCodePay != null) {
                    print(String.format(Locale.CHINA, "%s  ￥%.2f\n", qrCodePay.getTitle(), qrCodePay.getPrice()));
                }

                print("-------------------------------\n");
                print(PrintCmd.SetAlignment(1));
                print("谢谢惠顾\n");
            }

            print(PrintCmd.PrintFeedline(5));      // 走纸换行
            print(PrintCmd.PrintCutpaper(1));  // 切纸类型
            print(PrintCmd.SetClean());            // 清理缓存

        } catch (UnsupportedEncodingException e) {
            Log.e(TAG, "print: ", e);
        }
    }

    private void print(String line) throws UnsupportedEncodingException {
        mUsbDriver.write(line.getBytes("GBK"));
    }

    private void print(byte[] bytes) {
        mUsbDriver.write(bytes);
    }

    public interface OnConnectListener {
        void onConnected();
    }
}
